package com.example.zzx.dovebook.bookshare.booksharehome;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnFocusChange;
import butterknife.OnTextChanged;
import com.example.baselibrary.commonutil.FormatUtil;
import com.example.baselibrary.widget.BottomDialog;
import com.example.baselibrary.widget.LoadingStateView;
import com.example.library.GroupExpandAdapter;
import com.example.zzx.dovebook.R;
import com.example.zzx.dovebook.base.ValueWrapper;
import com.example.zzx.dovebook.base.model.BookShare;
import com.example.zzx.dovebook.bookshare.booksharedetail.BookShareDetailActivity;
import com.example.zzx.dovebook.bookshare.booksharehome.model.Comment;
import com.example.zzx.dovebook.bookshare.booksharehome.model.CommentReply;
import com.example.zzx.dovebook.login.LoginCheck;
import com.example.zzx.dovebook.user.UserManager;
import com.qmuiteam.qmui.util.QMUIKeyboardHelper;

import java.util.List;

import static com.example.zzx.dovebook.base.ValueWrapper.TYPE_FAILED;
import static com.example.zzx.dovebook.base.ValueWrapper.TYPE_NO_CONTENT;


public class CommentDialog extends BottomDialog {

    private static final String TAG = "CommentDialog";

    private String mBookShareId = "";

    private static final int TYPE_ADD_COMMENT = 0;
    private static final int TYPE_REPLY_COMMENT = 1;

    private int mSendType = TYPE_ADD_COMMENT;

    @BindView(R.id.comment_dialog_comment_count_tv)
    TextView commentCountTv;
    @BindView(R.id.comment_dialog_recycler)
    RecyclerView recycler;
    @BindView(R.id.comment_dialog_add_edit)
    EditText addEdit;
    @BindView(R.id.comment_dialog_send_img)
    ImageView sendImg;

    private GroupExpandAdapter mAdapter;

    private BookShareDetailActivity mContext;

    private Comment mReplyParentComment;
    private Comment mReply;
    private String mReplyToUserName;

    private LoadingStateView mEmptyView;
    private LoadingStateView mLoadMoreView;

    private long mLastCommentCreateAt;

    public CommentDialog(Context context) {
        super(context, R.layout.dialog_book_share_comment);
        mContext = (BookShareDetailActivity) context;
    }


    @OnClick(R.id.comment_dialog_back_img)
    public void back() {
        dismiss();
    }

    @OnFocusChange(R.id.comment_dialog_add_edit)
    public void onAddEditFocusChanged(View view, boolean hasFocus) {
        if (!hasFocus) {
            if (TextUtils.isEmpty(addEdit.getText().toString())) {
                mSendType = TYPE_ADD_COMMENT;
                addEdit.setHint("留下您的精彩评论吧");
            }
            QMUIKeyboardHelper.hideKeyboard(addEdit);
        }
    }

    @OnTextChanged(value = R.id.comment_dialog_add_edit, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void onAddEditTextChanged(Editable editable) {
        if (TextUtils.isEmpty(editable.toString())) {
            sendImg.setImageResource(R.drawable.ic_send_grey_24dp);
            sendImg.setClickable(false);
        } else {
            sendImg.setImageResource(R.drawable.ic_send_red_24dp);
            sendImg.setClickable(true);
        }
    }

    public void showReplyEdit(CommentReply reply, Comment replyParentComment) {
        mReply = new Comment();
        mReply.setBookShareId(replyParentComment.getBookShareId());
        mReply.setFromUserId(UserManager.getInstance(getContext()).getLoginUserId());
        mReply.setParentId(replyParentComment.getBookShareCommentId());
        mReply.setToUserId(reply.getReplyFromUserId());
        mReplyToUserName = reply.getReplyFromUserName();
        mReplyParentComment = replyParentComment;
        mSendType = TYPE_REPLY_COMMENT;
        addEdit.setHint("回复" + reply.getReplyFromUserName());
        addEdit.requestFocus();
        QMUIKeyboardHelper.showKeyboard(addEdit, 60);
    }

    public void showReplyEdit(Comment comment) {
        mReply = new Comment();
        mReply.setBookShareId(comment.getBookShareId());
        mReply.setFromUserId(UserManager.getInstance(getContext()).getLoginUserId());
        mReply.setParentId(comment.getBookShareCommentId());
        mReply.setToUserId(comment.getFromUserId());
        mReplyToUserName = comment.getUserName();
        mReplyParentComment = comment;
        mSendType = TYPE_REPLY_COMMENT;
        addEdit.setHint("回复" + comment.getUserName());
        addEdit.requestFocus();
        QMUIKeyboardHelper.showKeyboard(addEdit, 60);
    }

    @Override
    protected void initViews() {

        setupSendImg();

        setupRecyclerView();

    }

    private void setupSendImg() {
        sendImg.setOnClickListener( sendImg -> {
            addCommentToServer();
        });
        sendImg.setClickable(false);
    }


    private void setupRecyclerView() {
        mEmptyView = new LoadingStateView(getContext());
        mLoadMoreView = new LoadingStateView(getContext());
        mAdapter = new GroupExpandAdapter.Builder()
                .expandAll()
                .emptyView(mEmptyView)
                .addRooter(mLoadMoreView)
                .build();
        mAdapter.setOnLoadMoreListener((adaper) -> {
            if (mLoadMoreView.isNoMore()) {
                return ;
            }
            queryComments();
        });
        mEmptyView.setOnRetryListener((emptyView) -> {
            emptyView.loading();
            queryComments();
        });
        mEmptyView.setTextColor(ContextCompat.getColor(getContext(), R.color.text_color_secondary));
        mLoadMoreView.setTextColor(ContextCompat.getColor(getContext(), R.color.text_color_secondary));
        recycler.setAdapter(mAdapter);
    }

    public void addCommentToRecycler(@Nullable Comment comment) {
        if (mEmptyView.isEmpty()) {
            mAdapter.cancelEmptyState();
        }
        addEdit.clearFocus();
        mAdapter.addGroup(0, comment);
        recycler.scrollToPosition(0);
    }

    public void addCommentToRecycler(ValueWrapper wrapper) {
        if (wrapper.value == null) {
            if (mAdapter.getGroupSize() > 0) {
                mLoadMoreView.noMore();
            } else {
                if (wrapper.type == TYPE_FAILED) {
                    mEmptyView.failed();
                } else if (wrapper.type == TYPE_NO_CONTENT) {
                    mEmptyView.empty();
                }
            }
            return ;
        }
        List<Comment> commentList = (List<Comment>) wrapper.value;
        if (mAdapter.isInEmptyState()) {
            mAdapter.cancelEmptyState();
        }
        if (commentList.size() < 10) {
            mAdapter.addGroupList(commentList);
            mLoadMoreView.noMore();
        } else {
            mAdapter.addGroupList(commentList);
        }
    }

    @LoginCheck
    public void addCommentToServer() {
        if (mSendType == TYPE_ADD_COMMENT) {
            Comment comment = new Comment();
            comment.setBookShareId(mBookShareId);
            comment.setContent(addEdit.getText().toString());
            comment.setFromUserId(UserManager.getInstance(mContext).getLoginUserId());
            mContext.getViewModel().addComment(comment).observe(mContext,
                    commentResult -> addCommentToRecycler(commentResult));
        } else if (mSendType == TYPE_REPLY_COMMENT) {
            mReply.setContent(addEdit.getText().toString());
            mContext.getViewModel().replyComment(mReply).observe(mContext, reply -> {
                reply.setReplyToUserId(mReplyToUserName);
                reply.setReplyFromUserName(UserManager.getInstance(mContext).getLoginUserName());
                addReplyToRecycler(reply);
            });
        }
        addEdit.setText("");
        addEdit.clearFocus();
    }

    public void addReplyToRecycler(CommentReply reply) {
        mAdapter.addChild(0, reply, mReplyParentComment);
    }

    public void show(BookShare bookShare) {
        boolean refresh = false;
        if (mAdapter == null || mAdapter.getGroupSize() == 0) {
            refresh = true;
        }
        if (!TextUtils.equals(bookShare.getBookShareId(), mBookShareId)) {
            mBookShareId = bookShare.getBookShareId();
            refresh = true;
        }
        if (refresh) {
            setOnDialogShowListener(new OnDialogShowListener() {
                @Override
                public void onStartShow() {
                    refresh(bookShare);
                }

                @Override
                public void onAnimationFinish() {

                }
            });
        } else {
            setOnDialogShowListener(null);
        }
        super.show();
    }

    private void refresh(BookShare bookShare) {
        commentCountTv.setText(FormatUtil.countFormat(bookShare.getCommentCount()) + "条评论");
        mLastCommentCreateAt = 0;
        mAdapter.clearGroup();
        mAdapter.emptyState();
        mEmptyView.loading();
        mLoadMoreView.loading();
        queryComments();
    }

    private void queryComments() {
        if (mLastCommentCreateAt == 0) {
            mLastCommentCreateAt = System.currentTimeMillis();
        }
        if (mAdapter.getGroupSize() > 0) {
            ((Comment) mAdapter.getLastGroup()).getCreateAt();
        }
        String loginUserId = UserManager.getInstance(mContext).getLoginUserId();
        if (loginUserId == null) {
            loginUserId = "";
        }
        mContext.getViewModel().queryComments(loginUserId,
                mBookShareId, mLastCommentCreateAt)
                .observe(mContext, valueWrapper -> addCommentToRecycler(valueWrapper));
    }

    @Override
    public void dismiss() {
        addEdit.clearFocus();
        super.dismiss();
    }
}
